package me.zhengjie.modules.enrstu.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Data
public class EasyExcelUtil{
    public static <E> List<E> batchImport(Class<?> clazz, MultipartFile file, String sheetName) {

        List<E> returnDataList = new ArrayList<>();

        try {
            InputStream inputFile = file.getInputStream();
            // 这里 只要，然后读取第一个sheet 同步读取会自动finish
            EasyExcel.read(inputFile, clazz, new EasyExcelListenerData<>(returnDataList)).sheet(sheetName).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnDataList;
    }
    /**
     * onDataReady:数据读取完毕,回调传入的读取数据
     * @param dataList 数据列表
     */
    /**
     * 数据读取完毕回调
     */
    @Data
    private static class EasyExcelListenerData<E> extends AnalysisEventListener<E> {
        private final List<E> dataList;

        public EasyExcelListenerData(List<E> dataList) {
            this.dataList = dataList;
        }

        @Override
        public void invoke(E data, AnalysisContext context) {
            dataList.add(data);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // 所有数据解析完成后的操作
        }
    }

}
